<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900 py-12">
    <div class="container mx-auto px-4 max-w-4xl">
      <!-- 加载状态 -->
      <div v-if="loading" class="text-center py-12">
        <div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-blue-600 border-t-transparent"></div>
      </div>

      <!-- 文章内容 -->
      <article v-else-if="article" class="bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden">
        <div class="p-8 md:p-12">
          <!-- 分类和标签 -->
          <div class="flex flex-wrap items-center gap-2 mb-4">
            <span v-if="article.category" class="px-3 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 text-sm rounded-full">
              {{ article.category }}
            </span>
            <span v-if="article.isFeatured" class="px-3 py-1 bg-yellow-100 dark:bg-yellow-900/30 text-yellow-600 dark:text-yellow-400 text-sm rounded-full">
              精选
            </span>
          </div>

          <!-- 标题 -->
          <h1 class="text-4xl font-bold text-gray-900 dark:text-white mb-6">
            {{ article.title }}
          </h1>

          <!-- 元信息 -->
          <div class="flex flex-wrap items-center gap-6 text-sm text-gray-600 dark:text-gray-400 mb-8 pb-8 border-b border-gray-200 dark:border-gray-700">
            <div v-if="article.author" class="flex items-center gap-2">
              <div class="w-8 h-8 rounded-full bg-gradient-to-r from-blue-500 to-purple-500 flex items-center justify-center text-white font-semibold text-sm">
                {{ article.author.nickname?.charAt(0) || 'A' }}
              </div>
              <span>{{ article.author.nickname }}</span>
            </div>
            <div>{{ formatDate(article.publishedAt || article.createdAt) }}</div>
            <div class="flex items-center gap-1">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
              </svg>
              {{ article.views }} 阅读
            </div>
            <button
              @click="handleLike"
              class="flex items-center gap-1 hover:text-red-500 transition-colors"
              :class="{ 'text-red-500': liked }"
            >
              <svg class="w-4 h-4" :fill="liked ? 'currentColor' : 'none'" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
              </svg>
              {{ article.likes }}
            </button>
          </div>

          <!-- 文章内容 -->
          <div 
            class="prose prose-lg dark:prose-invert max-w-none mb-8"
            v-html="article.contentHtml || article.content"
          ></div>

          <!-- 标签 -->
          <div v-if="article.tags && article.tags.length > 0" class="flex flex-wrap gap-2 pt-8 border-t border-gray-200 dark:border-gray-700">
            <span
              v-for="tag in article.tags"
              :key="tag"
              class="px-3 py-1 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 text-sm rounded-full"
            >
              #{{ tag }}
            </span>
          </div>
        </div>
      </article>

      <!-- 相关工具推荐 -->
      <div v-if="recommendedTools.length > 0" class="mt-12">
        <div class="bg-gradient-to-r from-blue-50 to-purple-50 dark:from-gray-800 dark:to-gray-700 rounded-lg p-8">
          <div class="flex items-center gap-3 mb-6">
            <div class="w-10 h-10 rounded-lg bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
              <Icon name="heroicons:star" class="w-6 h-6 text-white" />
            </div>
            <div>
              <h2 class="text-2xl font-bold text-gray-900 dark:text-white">推荐工具</h2>
              <p class="text-sm text-gray-600 dark:text-gray-400">基于本文内容为您推荐以下工具</p>
            </div>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <NuxtLink
              v-for="tool in recommendedTools"
              :key="tool.id"
              :to="`/tools/${tool.slug}`"
              class="bg-white dark:bg-gray-800 rounded-lg p-5 hover:shadow-lg transition-all group border border-gray-200 dark:border-gray-700"
            >
              <!-- Logo 和名称 -->
              <div class="flex items-start gap-3 mb-3">
                <div class="w-12 h-12 rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-700 flex-shrink-0">
                  <img
                    v-if="tool.logo"
                    :src="tool.logo"
                    :alt="tool.name"
                    class="w-full h-full object-cover"
                  />
                  <div v-else class="w-full h-full flex items-center justify-center text-gray-400">
                    <Icon name="heroicons:cube" class="w-6 h-6" />
                  </div>
                </div>
                <div class="flex-1 min-w-0">
                  <h3 class="font-semibold text-gray-900 dark:text-white group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors truncate">
                    {{ tool.name }}
                  </h3>
                  <p class="text-sm text-gray-500 dark:text-gray-400 line-clamp-1">
                    {{ tool.description }}
                  </p>
                </div>
              </div>

              <!-- 评分和价格 -->
              <div class="flex items-center justify-between pt-3 border-t border-gray-100 dark:border-gray-700">
                <div class="flex items-center gap-1 text-sm">
                  <Icon name="heroicons:star-solid" class="w-4 h-4 text-yellow-400" />
                  <span class="font-medium text-gray-900 dark:text-white">{{ formatRating(tool.rating) }}</span>
                  <span class="text-gray-400">·</span>
                  <span class="text-gray-500 dark:text-gray-400">{{ tool?.reviewCount || 0 }}条评价</span>
                </div>
                <div v-if="tool.isFree" class="px-2 py-1 bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400 text-xs rounded font-medium">
                  免费
                </div>
              </div>
            </NuxtLink>
          </div>

          <div class="mt-6 text-center">
            <NuxtLink
              to="/tools"
              class="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all font-medium"
            >
              <Icon name="heroicons:sparkles" class="w-5 h-5" />
              发现更多工具
            </NuxtLink>
          </div>
        </div>
      </div>

      <!-- 相关文章 -->
      <div v-if="relatedArticles.length > 0" class="mt-12">
        <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-6">相关文章</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <NuxtLink
            v-for="related in relatedArticles"
            :key="related.id"
            :to="`/articles/${related.slug}`"
            class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 hover:shadow-md transition-shadow"
          >
            <div v-if="related.category" class="text-sm text-blue-600 dark:text-blue-400 mb-2">
              {{ related.category }}
            </div>
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">
              {{ related.title }}
            </h3>
            <p class="text-sm text-gray-600 dark:text-gray-400 line-clamp-2">
              {{ related.excerpt }}
            </p>
          </NuxtLink>
        </div>
      </div>

      <!-- 返回按钮 -->
      <div class="mt-12 text-center">
        <NuxtLink
          to="/articles"
          class="inline-flex items-center gap-2 px-6 py-3 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
        >
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
          返回文章列表
        </NuxtLink>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useArticles } from '~/composables/useArticles'
import { useTools } from '~/composables/useTools'
import type { Article, Tool } from '~/types'

const route = useRoute()
const { getArticle, getRelatedArticles, likeArticle } = useArticles()
const { getFeaturedTools } = useTools()

const article = ref<Article | null>(null)
const relatedArticles = ref<Article[]>([])
const recommendedTools = ref<Tool[]>([])
const loading = ref(true)
const liked = ref(false)

const loadArticle = async () => {
  try {
    loading.value = true
    const slug = route.params.slug as string
    article.value = await getArticle(slug)
    
    // 加载相关文章
    if (article.value) {
      relatedArticles.value = await getRelatedArticles(article.value.id)
      
      // 加载推荐工具（这里简单使用特色工具，实际可以根据文章标签/分类智能推荐）
      recommendedTools.value = await getFeaturedTools(6)
    }
  } catch (error) {
    console.error('加载文章失败:', error)
  } finally {
    loading.value = false
  }
}

const handleLike = async () => {
  if (!article.value || liked.value) return
  
  try {
    await likeArticle(article.value.id)
    article.value.likes += 1
    liked.value = true
  } catch (error) {
    console.error('点赞失败:', error)
  }
}

const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
}

const formatRating = (rating: number | string): string => {
  const num = typeof rating === 'string' ? parseFloat(rating) : rating
  return num.toFixed(1)
}

onMounted(() => {
  loadArticle()
})

// SEO配置和结构化数据
const config = useRuntimeConfig()
const siteUrl = config.public.siteUrl || 'http://localhost:3000'
const { generateArticleSchema, generateBreadcrumbSchema } = useSEO()

useHead(() => {
  const title = article.value?.metaTitle || article.value?.title || 'DevTools Hub'
  const description = article.value?.metaDescription || article.value?.excerpt || ''
  const url = `${siteUrl}/articles/${route.params.slug}`
  
  // 生成结构化数据
  const scripts: any[] = []
  if (article.value) {
    // 文章 Schema
    scripts.push({
      type: 'application/ld+json',
      innerHTML: JSON.stringify(generateArticleSchema({
        title: article.value.title,
        description: article.value.excerpt || description,
        url,
        author: article.value.author?.nickname || 'DevToolsHub',
        publishDate: article.value.publishedAt || article.value.createdAt,
        modifiedDate: article.value.updatedAt,
        image: article.value.coverImage,
      })),
    })
    
    // 面包屑 Schema
    scripts.push({
      type: 'application/ld+json',
      innerHTML: JSON.stringify(generateBreadcrumbSchema([
        { name: '首页', url: siteUrl },
        { name: '文章', url: `${siteUrl}/articles` },
        { name: article.value.title, url }
      ])),
    })
  }
  
  return {
    title,
    meta: [
      {
        name: 'description',
        content: description,
      },
      {
        name: 'keywords',
        content: article.value?.metaKeywords?.join(', ') || article.value?.tags?.join(', ') || '',
      },
      // Open Graph
      {
        property: 'og:title',
        content: title,
      },
      {
        property: 'og:description',
        content: description,
      },
      {
        property: 'og:type',
        content: 'article',
      },
      {
        property: 'og:url',
        content: url,
      },
      // Twitter Card
      {
        name: 'twitter:card',
        content: 'summary_large_image',
      },
      {
        name: 'twitter:title',
        content: title,
      },
      {
        name: 'twitter:description',
        content: description,
      },
    ],
    link: [
      { rel: 'canonical', href: url },
    ],
    script: scripts,
  }
})
</script>

<style>
/* Prose样式 - 用于渲染Markdown内容 */
.prose {
  color: inherit;
}

.prose h1,
.prose h2,
.prose h3,
.prose h4 {
  color: inherit;
  font-weight: 600;
  margin-top: 2em;
  margin-bottom: 1em;
}

.prose h1 {
  font-size: 2em;
}

.prose h2 {
  font-size: 1.5em;
}

.prose h3 {
  font-size: 1.25em;
}

.prose p {
  margin-top: 1.25em;
  margin-bottom: 1.25em;
}

.prose ul,
.prose ol {
  margin-top: 1.25em;
  margin-bottom: 1.25em;
  padding-left: 1.625em;
}

.prose li {
  margin-top: 0.5em;
  margin-bottom: 0.5em;
}

.prose code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 0.2em 0.4em;
  border-radius: 0.25em;
  font-size: 0.875em;
}

.dark .prose code {
  background-color: rgba(255, 255, 255, 0.1);
}

.prose pre {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 1em;
  border-radius: 0.5em;
  overflow-x: auto;
}

.dark .prose pre {
  background-color: rgba(255, 255, 255, 0.05);
}

.prose a {
  color: #3b82f6;
  text-decoration: underline;
}

.prose a:hover {
  color: #2563eb;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>

